#!/usr/local/bin/python
################################################################################
# manager.py
#
# UTF8SMTP NIDAMail Program
# Version 1.0
# Date : July 23, 2008
# Homepage: http://sourceforge.net/projects/utf8smtp/
################################################################################
from subprocess import *
import os, sys, time

import common

# Configuration
conf = common.conf
vh = common.vh
access = common.access

pid_list = {}
process_list = ['%s/bin/encoder' % conf['BASE_PATH'],
  	        '%s/bin/sender' % conf['BASE_PATH'],
	        '%s/bin/decoder' % conf['BASE_PATH'],
	        '%s/bin/esmtpd' % conf['BASE_PATH']]
if conf['POP3D_TYPE'] != 'none': process_list.append('%s/bin/pop3d' % conf['BASE_PATH'])

def printUsage():
    print ""
    print "  You must run as a 'root'."
    print "  Usage: %s/bin/manager {start | stop}" % conf['BASE_PATH']
    print ""

if len(sys.argv) != 2: printUsage()
elif sys.argv[1].strip().lower() == 'start':
    if os.path.exists('%s/pid' % conf['BASE_PATH']):
        print "%s is already running" % common.PROGRAM_NAME
        os._exit(0)
    pid = os.fork()
    if pid != 0: os._exit(0)
    os.setpgrp()
    os.umask(0)
   
    f = open('%s/pid' % conf['BASE_PATH'], 'w')
    pids = '%d ' % os.getpid()
    for process_path in process_list:
        process = process_path.split('/')[-1]
        p = Popen(process_path)
        pid_list[process] = p
        pids += '%d ' % p.pid
    f.write(pids)
    f.close()
    common.printLOG('manager | %s is started' % common.PROGRAM_NAME, 'common')
    print '%s is started' % common.PROGRAM_NAME
    while 1:
        status = 0
        pids = '%d ' % os.getpid()
        for process in pid_list.keys():
            p = pid_list[process]
            if p.poll():
                p = Popen('%s/bin/%s' % (conf['BASE_PATH'], process))
                pid_list[process] = p
                status = 1
            pids += '%d ' % p.pid
        if status == 1:
            f = open('%s/pid' % conf['BASE_PATH'], 'w')
            f.write(pids)
            f.close()
        time.sleep(1)
elif sys.argv[1].strip().lower() == 'stop':
    if not os.path.exists('%s/pid' % conf['BASE_PATH']): print "%s is not running" % common.PROGRAM_NAME
    else:
        f = open('%s/pid' % conf['BASE_PATH'], 'r')
        os.system('kill -9 %s' % f.read())
        f.close()
        os.unlink('%s/pid' % conf['BASE_PATH'])
        common.printLOG('manager | %s is stopped' % common.PROGRAM_NAME, 'common')
        print '%s is stopped' % common.PROGRAM_NAME
else: printUsage()

################################################################################
# End of File
################################################################################